from pattern.circuit import Control


class entry(Control):
    
    class FakeWindow(object):
        
        def emit(self, e4shape, cb, **kwargs):
            print "Emitting", e4shape, cb
            self._call(e4shape, cb, **kwargs)

        def call(self, e4shape, cb, **kwargs):
            print "Calling", e4shape, cb
            return self._call(e4shape, cb, **kwargs)

        def _call(self, e4shape, cb, **kwargs):
            import codebase
            import pattern.circuit
            import weakref
            component = codebase.getComponent(e4shape)
            if hasattr(component, cb):
                e = pattern.circuit.Event()
                e._weak_window = weakref.ref(self)
                e._weak_shape = weakref.ref(e4shape)
                for key, value in kwargs.items():
                    setattr(e, key, value)
                return getattr(component, cb)(e)
           
    def __init__(self):
        self.window = self.FakeWindow()

    def incoming(self, event):
        subordinate = self.subordinate(event)
        self.window.emit(subordinate, "incoming", data=event.data)

    def please(self, event):
        subordinate = self.subordinate(event)
        return self.window.call(subordinate, "please", data=event.data)

    def subordinate(self, event):
        subordinate = [x for x in event.window.shapes 
            if getattr(x, 'tag', '') == event.shape.id]
        if len(subordinate) == 0:
            raise KeyError, event.shape.id + ' not found'
        elif len(subordinate) > 1:
            raise KeyError, 'ambiguous ' + event.shape.id
        
        return subordinate[0]
        